package com.itcam.thread_;

/**
 * Author:Cammy.Wu
 * Date:2024-05-11
 * Description:
 */

import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock锁
 *      使用Lock锁，我们可以更清晰的看到哪里加了锁，哪里释放了锁
 *
 *      Lock是接口，无法直接创建对象
 *          构造方法：
 *              public ReentrantLock(); 创建一个ReentantLock的实例互斥锁
 *          成员方法：
 *              void lock(); 加锁
 *              void unlock(); 释放锁
 */

public class ThreadTest06 {
    public static void main(String[] args) {
        TicketTask6 task = new TicketTask6();

        Thread t1 = new Thread(task, "窗口1");
        Thread t2 = new Thread(task, "窗口2");
        Thread t3 = new Thread(task, "窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class TicketTask6 implements Runnable {

    private int ticket = 100;
    private ReentrantLock lock = new ReentrantLock();


    /**
     * When an object implementing interface {@code Runnable} is used
     * to create a thread, starting the thread causes the object's
     * {@code run} method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method {@code run} is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (ticket == 0) {
    //                lock.unlock();
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "卖出了第" + ticket + "张票");
                ticket--;
//                lock.unlock();
            } finally {
                lock.unlock();
            }
        }
    }
}